import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {adSystemApiUrl, AliyunOssOutputUrl} from '../../../../../config/api';
import {AdOssUploadService} from '../../../../lib/service/ad-oss-upload.service';
import {HttpService} from '../../../../lib/service/http.service';
import {ModifyArticle} from '../../article-manage';
import {EditorComponent} from '../../../../comm-components/wangeditor/editor.component';

@Component({
  selector: 'app-add-place',
  templateUrl: 'modify.component.html',
  styleUrls: ['modify.component.scss'],
  providers: []
})
export class ModifyComponent implements OnInit {

  id: number;  // 文章ID
  modifyArticle = new ModifyArticle();
  aliyunOssoutputurl = AliyunOssOutputUrl;
  classifyList: any;
  type = 'success';
  message = '修改成功';
  isShow = false;
  img_file: any;
  img_name: string;
  img_url: string;

  changedImg = false;  // 是否更改过图片
  @ViewChild(EditorComponent) editor: EditorComponent;
  constructor(private httpService: HttpService,
              private route: ActivatedRoute,
              private adOssUploadService: AdOssUploadService) {
  }

  ngOnInit() {
    this.getClassifyList();
      this.editor.changedEitorUsePlace('article');
    this.getDetail();
  }

  // 获取分类列表
  getClassifyList() {
    const url = `${adSystemApiUrl}/v1/admin/category/list`;
    return this.httpService.httpGetAuth(url)
      .subscribe(
        data => {
          this.classifyList = data.data;
        }
      );
  }

  // 获取文章详情
  getDetail() {
    this.id = +this.route.snapshot.params['id'];
    const url = `${adSystemApiUrl}/v1/admin/posts/detail?postID=${this.id}`;
    return this.httpService.httpGetAuth(url)
      .subscribe(
        data => {
          this.modifyArticle.postID = data.data.id;
          this.modifyArticle.author_id = data.data.author_id;
          this.modifyArticle.category_id = data.data.category_id;
          this.modifyArticle.title = data.data.title;
          this.modifyArticle.seo_title = data.data.seo_title;
          this.modifyArticle.excerpt = data.data.excerpt;
          this.modifyArticle.image = data.data.image;
          this.modifyArticle.meta_keywords = data.data.meta_keywords;
          this.modifyArticle.meta_description = data.data.meta_description;
          this.modifyArticle.status = data.data.status;
          this.modifyArticle.featured = data.data.featured;
          this.modifyArticle.image = data.data.image;
          this.modifyArticle.slug = data.data.slug;
          this.img_url = this.aliyunOssoutputurl + '/' + data.data.image;
          if (data.data.status === '发布') {
            this.modifyArticle.status = '1';
          } else if (data.data.status === '草稿') {
            this.modifyArticle.status = '2';
          } else {
            this.modifyArticle.status = '3';
          }
          this.editor.loadingHandle(data.data.body);
        }
      );
  }

  // 上传图片
  uploadImg($event: any) {
    this.changedImg = true;
    const file = $event.path[0].files[0];
    const myReader = new FileReader();
    const self = this;
    const suffix = file.name.replace(/.+\./, '').toLowerCase();
    this.img_file = file;
    const now = new Date();
    this.img_name = now.getTime() + '.' + suffix;
    myReader.readAsDataURL(file);
    myReader.onloadend = function (e) {
      self.img_url = myReader.result;
    };
  };

  // 提交文章
  submitForm() {
    this.modifyArticle.body = this.editor.clickHandle();
    const url = `${adSystemApiUrl}/v1/admin/posts/edit`;
    return this.httpService.httpPostAuth(url, this.modifyArticle)
      .subscribe(
        res => {
          if (res.code === 2000) {
            if (this.changedImg) {
              this.adOssUploadService.getSignature('/v1/common/post/' + this.modifyArticle.postID + '?callback=true').subscribe(
                res1 => {
                  this.adOssUploadService.fileUpload(this.img_file, res1.data, this.img_name, 'image').subscribe(
                    res2 => {
                      if (res2.status === 200) {
                        this.type = 'success';
                        this.message = '文章修改成功';
                        this.isShow = true;
                      } else {
                        this.type = 'error';
                        this.message = '图片上传失败';
                        this.isShow = true;
                      }
                    }
                  );
                }
              );
            } else {
              this.type = 'success';
              this.message = '文章修改成功';
              this.isShow = true;
            }
          } else {
            this.type = 'error';
            this.message = res.message;
            this.isShow = true;
          }
        }
      );
  }

    PostData(event): void {}
}
